"use client";

import { type ReactNode, createContext, useRef, useContext } from "react";
import { useStoreWithEqualityFn } from "zustand/traditional";

import {
  createCustomizationStore,
  CustomizationStore,
} from "../stores/customization-store";

export type StoreApi = ReturnType<typeof createCustomizationStore>;

export const StoreContext = createContext<StoreApi | undefined>(undefined);

export interface StoreProviderProps {
  children: ReactNode;
  customization: Customization;
}

export const CustomizationStoreProvider = ({
  children,
  customization,
}: StoreProviderProps) => {
  const storeRef = useRef<StoreApi>();
  if (!storeRef.current) {
    storeRef.current = createCustomizationStore({ ...customization });
  }

  return (
    <StoreContext.Provider value={storeRef.current}>
      {children}
    </StoreContext.Provider>
  );
};

export const useCustomizationStore = <T,>(
  selector: (store: CustomizationStore) => T,
  equalityFn?: (a: T, b: T) => boolean
): T => {
  const customizationStoreContext = useContext(StoreContext);

  if (!customizationStoreContext) {
    throw new Error(`useCounterStore must be used within CounterStoreProvider`);
  }

  return useStoreWithEqualityFn(
    customizationStoreContext,
    selector,
    equalityFn
  );
};
